﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using BUS;
using System.Runtime.InteropServices;

using System.Collections;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Net.NetworkInformation;

using AForge;
using AForge.Video;
using AForge.Video.DirectShow;

namespace GPBenhLanh
{
    public partial class frmChupHinh_AF : DevExpress.XtraEditors.XtraForm
    {
        public frmChupHinh_AF()
        {
            InitializeComponent();
        }
        public frmChupHinh_AF(string _sotieuban, int _isCl)
        {
            InitializeComponent();
            sotieuban = _sotieuban;
           
            isCl = _isCl;
        }


        private string pathTemp = "";
        public string sThuMucLuu = "";
        public string sThuGoc = "";
        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        public string sotieuban = "";
        public string DVuCode = "";
        public string sophieu = "";
        public int isCl = 0;
        private int flag = 0;
        private int[] isImg = new int[4]{0,0,0,0} ;
        public delegate void DelegeChupH(object sender, Object data);
        public event DelegeChupH thoatEven;


        private FilterInfoCollection captureDriver;
        private VideoCaptureDevice finalFrame;
        double br = 0;
        double ct = 0;
        Bitmap img;
        void finalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            img = (Bitmap)eventArgs.Frame.Clone();

            //br = Convert.ToDouble(txtdosang.Text) * 10;
            //BitmapFilter.Brightness(img, (float)br);//tang do sang 

            //ct = (float)br - ((float)br * 0.15);
            //BitmapFilter.Contrast(img, (sbyte)ct);//tang do sang 

            pictureBox1.Image = img;

            img = null;
        }

        private void frmChupHinh_Load(object sender, EventArgs e)
        {
            try
            {
                //load lai hinh neu da chup roi                
                txtsohs.Text = "";
                txtsobn.Text = "";
                txtSoTieuBan.Text = sotieuban;

                txtdiachi.Text = "";
                txtGioi.Text = "";
                txtHoTen.Text = "";
                txttendv.Text = "";
                txtTuoi.Text = "";

                pathTemp = Application.StartupPath + "\\PictureTemp";
                sThuGoc = sThuMucLuu + "\\";
                if (!Directory.Exists(pathTemp))
                {
                    Directory.CreateDirectory(pathTemp);
                }
                if (isCl == 1)
                {
                    txtSoTieuBan.Enabled = false;
                    btnNext.Visible = false;
                    btnPrevious.Visible = false;
                    btngo.Visible = false;
                    btngo_Click(sender, e);
                }
                else
                {
                    txtSoTieuBan.Enabled = true;
                }             

                /***++++++++++++++++++++++++++++++++++++++++++++++*/
                captureDriver = new FilterInfoCollection(FilterCategory.VideoInputDevice);
              
                if (captureDriver.Count > 0)
                {
                    finalFrame = new VideoCaptureDevice();                   
                    finalFrame = new VideoCaptureDevice(captureDriver[0].MonikerString);                    
                    finalFrame.NewFrame += new NewFrameEventHandler(finalFrame_NewFrame);
                    
                    finalFrame.Start();
                }
                else
                {
                    MessageBox.Show("Không có thiết bị nào đang kết nối!","Thông báo");
                    this.Close();
                    
                    return;
                }
                /***++++++++++++++++++++++++++++++++++++++++++++++*/
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH" + ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="urlTemp">url tren may local</param>
        /// <param name="urlSer">url tren may server</param>
        public void ReloadImage(string urlTemp, string urlSer)
        {
            //load hinh x100
            string urlLocal1 = "";
            string urlServ1 = "";
            string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None);
            string sobn = "";

            if (words.Length > 1)
                sobn = words[0] + "_" + words[1];
            else
                sobn = txtsobn.Text;
            DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
            int NhomPL = 0;
            if (dtPL.Rows.Count > 0)
                NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
            //if (DVuCode == "GE56" && isCl == 1)
            if (NhomPL == 1 && isCl == 1)
            {
                urlLocal1 = urlTemp + "x100_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
                urlServ1 = urlSer + "x100_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
            }
            else
            {
                urlLocal1 = urlTemp + "x100_" + txtSoTieuBan.Text + ".jpg";
                urlServ1 = urlSer + "x100_" + txtSoTieuBan.Text + ".jpg";
            }

            if (File.Exists(urlLocal1))
            {
                LoadHinh(pic100, urlLocal1);
            }
            else if (File.Exists(urlServ1))
            {
                LoadHinh(pic100, urlServ1);
            }
            else
            {
                ClearHinh(1);
                if (pic100.Name == "pic100")
                {
                    bmHinh1 = null;
                    pic100.Image = null;
                }
            }

            //load hinh x400
            string urlLocal2 = "";
            string urlServ2 = "";

            //if (DVuCode == "GE56" && isCl == 1)
            if (NhomPL == 1 && isCl == 1)
            {
                urlLocal2 = urlTemp + "\\x400_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
                urlServ2 = urlSer + "\\x400_" + txtSoTieuBan.Text + "_" + isCl.ToString() + ".jpg";
            }
            else
            {
                urlLocal2 = urlTemp + "x400_" + txtSoTieuBan.Text + ".jpg";
                urlServ2 = urlSer + "\\x400_" + txtSoTieuBan.Text + ".jpg";
            }
            if (File.Exists(urlLocal2))//neu co hinh o local thi load o local 
            {
                LoadHinh(pic400, urlLocal2);
            }
            else if (File.Exists(urlServ2))//neu co hinh o server thi load o local
            {
                LoadHinh(pic400, urlServ2);
            }
            else
            {
                ClearHinh(2);
                if (pic400.Name == "pic400")
                {
                    bmHinh2 = null;
                    pic400.Image = null;
                }
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {               
                ClearHinh(0);
                if (isCl == 1)
                {
                    if (thoatEven != null)
                    {
                        thoatEven(this, isImg);
                    }
                }
                this.Close();                
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// clear hinh tren picbox
        /// </summary>
        /// <param name="NumHinh">1: hinh 1; 2: hinh; 0: all</param>
        private void ClearHinh(int NumHinh)
        {
            if (NumHinh == 1)
            {
                if (bmHinh1 != null)
                {
                    bmHinh1.Dispose();
                    bmHinh1 = null;
                    pic100.Image = null;
                    pic100.Refresh();
                }
            }
            else if (NumHinh == 2)
            {
                if (bmHinh2 != null)
                {
                    bmHinh2.Dispose();
                    bmHinh2 = null;
                    pic400.Image = null;
                    pic400.Refresh();
                }
            }
            else if (NumHinh == 0)
            {
                if (bmHinh1 != null)
                {
                    bmHinh1.Dispose();
                    bmHinh1 = null;
                    pic100.Image = null;
                    pic100.Refresh();
                }
                if (bmHinh2 != null)
                {
                    bmHinh2.Dispose();
                    bmHinh2 = null;
                    pic400.Image = null;
                    pic400.Refresh();
                }
            }
        }

        private void LuuImage(string PreName, int imgTimes)
        {
           
                string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None);
                string sobn = "";
                if (words.Length > 1)
                    sobn = words[0] + "_" + words[1];
                else
                    sobn = txtsobn.Text;

                string ThuMucLuu = sThuMucLuu;
               
                string pathHinh1Ser = "";
                string pathStr = "";
                string pathStrbF = "";//Hinh truoc chinh sua
             
                DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(DVuCode);
                int NhomPL = 0;
                if (dtPL.Rows.Count > 0)
                    NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());

                if (NhomPL == 1 && isCl == 1)
                {
                    pathStr = pathTemp + PreName + sotieuban + "_" + isCl.ToString() + ".jpg";
                    pathStrbF = pathTemp + PreName + sotieuban + "bf_" + isCl.ToString() + ".jpg";
                    pathHinh1Ser = ThuMucLuu + PreName + sotieuban + "_" + isCl.ToString() + ".jpg";
                }
                else
                {
                    pathStr = pathTemp + PreName + sotieuban + ".jpg";
                    pathStrbF = pathTemp + PreName + sotieuban + "bf_" + ".jpg";
                    pathHinh1Ser = ThuMucLuu + PreName + sotieuban + ".jpg";
                }

               
               
                //save image to temp directory
                if (imgTimes == 1)
                {
                    if (pic100.Image != null)
                    {
                        pic100.Image.Save(pathStrbF, ImageFormat.Jpeg);
                        ChinhDoSang(pathStrbF, pathStr);
                        LoadHinh(pic100, pathStr); ;
                    }
                }
                if (imgTimes == 2)
                {
                    if (pic400.Image != null)
                    {
                        pic400.Image.Save(pathStrbF, ImageFormat.Jpeg);
                        ChinhDoSang(pathStrbF, pathStr);
                        pic400.Image = null;
                        LoadHinh(pic400, pathStr);
                    }
                }

                if (File.Exists(pathStr))
                {
                    flag = 1;
                    isImg[0] = 1;
                    /// if not exists directory then create directory
                    if (!Directory.Exists(ThuMucLuu))
                    {
                        Directory.CreateDirectory(ThuMucLuu);
                    }
                    ///delete if exists
                    if (File.Exists(pathHinh1Ser))
                    {
                        File.Delete(pathHinh1Ser);
                    }
                    //copy hinh to server
                    File.Copy(pathStr, pathHinh1Ser);

                    ///delete file local
                    File.Delete(pathStr);
                }
            
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                ClearHinh(1);
                LuuImage(  "\\x100_",1);
                ClearHinh(2);
                LuuImage("\\x400_",2);               
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
                return;
            }
            finally
            {             
                flag = 1;
                if (thoatEven != null)
                {
                    thoatEven(this, isImg);
                }
            }
        }

        private void xoaHinh(string path, PictureEdit edit)
        {           
            if (File.Exists(path))
            {
                if (edit.Name == "pic100")
                {
                   
                    if (bmHinh1 != null)
                    {                       
                        bmHinh1.Dispose();
                        pic100.Image = null;
                    }
                    File.Delete(path);
                }
                if (edit.Name == "pic400")
                {                   
                    if (bmHinh2 != null)
                    {
                        bmHinh2.Dispose();
                        pic400.Image = null;
                    }
                    File.Delete(path);
                }   
                
            }           
        }

        private void LoadHinh(PictureBox edit, string pathStr)
        {
            if (File.Exists(pathStr))
            {
                if (edit.Name == "pic100")
                {
                    Stream stream = File.Open(pathStr, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                    bmHinh1 = (Bitmap)Bitmap.FromStream(stream);
                    stream.Close();
                    edit.Image = bmHinh1;
                }

                if (edit.Name == "pic400")
                {
                    Stream stream = File.Open(pathStr, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                    bmHinh2 = (Bitmap)Bitmap.FromStream(stream);
                    stream.Close();
                    edit.Image = bmHinh2;
                }
            }
            
        }

        private void ChinhDoSang(string pathStrbf,string pathStr)
        {
            Bitmap m_Bitmap;
            float value = float.Parse(txtdosang.Text) * 10;
            if (value != 0)
            {               
                //doc file
                Stream stream = File.Open(pathStrbf, FileMode.Open,
                                        FileAccess.ReadWrite, FileShare.Delete);
                m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();

                BitmapFilter.Brightness(m_Bitmap, value);//tang do sang 
                BitmapFilter.Contrast(m_Bitmap, (sbyte)value);//tang do net

                ///crop image
                Rectangle cropRect = new Rectangle(10, 3, m_Bitmap.Width - 20, m_Bitmap.Height - 4);
                Bitmap target = new Bitmap(m_Bitmap);
                target = (Bitmap)cropImage(m_Bitmap, cropRect);

                target.Save(pathStr, ImageFormat.Jpeg);//save file moi chup thanh file moi 
                File.Delete(pathStrbf);//xoa file goc di
            }
            else
            {
                //doc file
                Stream stream = File.Open(pathStrbf, FileMode.Open,
                    FileAccess.ReadWrite, FileShare.Delete);
                m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Bitmap target = new Bitmap(m_Bitmap);
                target.Save(pathStr, ImageFormat.Jpeg);
            }
           

        }

        /// <summary>
        /// crop image to new size
        /// </summary>
        /// <param name="img">bitmap to crop</param>
        /// <param name="cropArea"> rectangle crop</param>
        /// <returns></returns>
        private static Image cropImage(Bitmap img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {            
            try
            {
                /*======================save image====================*/                
                Image old = pic100.Image;               
                if (old != null)
                    old.Dispose();

                int nW = hensu.newW;
                int nH = hensu.newH; 

                Bitmap img = new Bitmap((Bitmap)pictureBox1.Image.Clone());
                if (img.Width < nW)
                {
                    nW = img.Width;
                }

                if (img.Height < nH)
                {
                    nH = img.Height;
                }

                pic100.Image = new Bitmap(img, new Size(nW, nH));
                
                LuuImage("\\x100_", 1);
                p100 = 0;
                /*======================end save image====================*/
                   
            }
            catch(Exception ex)
            {
                MessageBox.Show("CH" + ex.Message.ToString(), "Thông Báo");                
                return;
            }
        }
        /// <summary> buffer for bitmap data. </summary>
        private byte[] savedArray;
        private bool captured = true;
        private int bufferedSize;
        private int p100 = 0, p400 = 0;
       

        private void btnChupHinhX400_Click(object sender, EventArgs e)
        {                        
            try
            {
                /*======================save image====================*/
                Image old = pic400.Image;
                if (old != null)
                    old.Dispose();

                int nW = hensu.newW;
                int nH = hensu.newH; 

                Bitmap img = new Bitmap((Bitmap)pictureBox1.Image.Clone());
                if (img.Width < nW)
                {
                    nW = img.Width;
                }

                if (img.Height < nH)
                {
                    nH = img.Height;
                }

                pic400.Image = new Bitmap(img, new Size(nW, nH));                          

                LuuImage("\\x400_", 2);
                p400 = 0;
                /*======================end save image====================*/
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH" + ex.Message.ToString(), "Thông Báo");
                return;
            }
        }

        private void frmChupHinh_FormClosing(object sender, FormClosingEventArgs e)
        {
            ClearHinh(0);
            this.Hide();
            if(finalFrame!= null)
                finalFrame.Stop();
        }

        private void frmChupHinh_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {      
                if (e.KeyCode == Keys.F9)
                {
                    //p100 = 1;
                    btnChupHinh_Click(sender, e);
                }
                else if (e.KeyCode == Keys.F10)
                {
                    //p400 = 1;
                    btnChupHinhX400_Click(sender, e);
                }
                else if (e.KeyCode == Keys.F11)
                {
                    btnLuu_Click(sender, e);
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    btnThoat_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH-" + ex.Message.ToString(), "Thông Báo");
            }
        }
        /// <summary>
        /// Lay chuoi tu phai sang theo leng truyen vao
        /// </summary>
        /// <param name="value">chuoi can cat</param>
        /// <param name="length">chieu dai can cat</param>
        /// <returns>chuoi can cat</returns>
        public string Right(string value, int length)
        {
            if (value == "")
                return "";
            else
                return value.Substring(value.Length - length);
        }

        /// <summary>
        /// hàm lấy chuỗi từ trái sang
        /// </summary>
        /// <param name="value">giá trị của chuỗi cần cắt</param>
        /// <param name="length">chiều dài cảu chuỗi con</param>
        /// <returns>cuỗi cần lấy</returns>
        public string Left(string value, int length)
        {
            if (value == "")
                return "";
            else
                return value.Substring(0, length);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int numCur = 0, numNext = 0;
            string pre = "";
            if (txtSoTieuBan.Text == "")
                return;
            numCur = int.Parse(Right(txtSoTieuBan.Text, hensu.LengTeBao));
            if (numCur >= 1)
                btnPrevious.Enabled = true;
            numNext = numCur + 1;
            if (isCl == 1)//dang chup hinh cho cat lanh
            {
                pre = Left(txtSoTieuBan.Text, 5);

                txtSoTieuBan.Text = pre + numNext.ToString("0000");
            }
            else// dang chup hinh cho gpb
            {
                pre = Left(txtSoTieuBan.Text, 4);
                txtSoTieuBan.Text = pre + numNext.ToString("00000");
            }
            btngo_Click(sender, e);
        }
        private void CreateDir(DateTime NgNhan)
        {
            string goc = sThuGoc;
            DateTime dt;
            if (!NgNhan.Equals(""))
                dt = NgNhan;
            else
                dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)+"\\";
        }

        private void btngo_Click(object sender, EventArgs e)
        {
            string SoTieuBan = txtSoTieuBan.Text;
            if (SoTieuBan.Equals(""))
                return;
            
            DataTable dt = GetThongTinSearchBUS.SearchDaXacNhanBySoTB(SoTieuBan);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    btnChupHinh.Enabled = true;
                    btnChupHinhX400.Enabled = true;
                    btnLuu.Enabled = true;

                    DateTime NgayNhan = DateTime.Parse(dt.Rows[0]["ngaynhan"].ToString());
                    CreateDir(NgayNhan);

                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString();
                    txtTuoi.Text = dt.Rows[0]["namsinh"].ToString()
                                 + "(" + dt.Rows[0]["tuoi"].ToString() + " Tuổi)";
                    txtGioi.Text = dt.Rows[0]["gioi"].ToString();
                    txtdiachi.Text = dt.Rows[0]["DiaChi"].ToString();
                    txttendv.Text = dt.Rows[0]["tendvu"].ToString();
                    txtsohs.Text = dt.Rows[0]["SoHS"].ToString();
                    txtsobn.Text = dt.Rows[0]["SoBN"].ToString();
                    sotieuban = txtSoTieuBan.Text;
                                     
                    ReloadImage(pathTemp, sThuMucLuu);
                    //tao folder tam tren local de luu hinh
                    string[] words = txtsobn.Text.Split(new string[] { "*" }, StringSplitOptions.None); 
                     string stb = "";
                     if (words.Length > 1)                        
                         stb = words[0] + "_" + words[1];                        
                     else
                         stb = txtsobn.Text;
                     pathTemp = Application.StartupPath + "\\PictureTemp" ;
                   
                    if (!Directory.Exists(pathTemp))
                    {
                        Directory.CreateDirectory(pathTemp);
                    }
                }
                else
                {
                    txtHoTen.Text = "";
                    txtTuoi.Text = "";
                    txtGioi.Text = "";
                    txtdiachi.Text = "";
                    txttendv.Text = "";
                    txtsohs.Text = "";
                    txtsobn.Text = "";
                }
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            int numCur = 0, numPrev = 0;
            string pre = "";
            if (txtSoTieuBan.Text == "")
                return;
            numCur = int.Parse(Right(txtSoTieuBan.Text, hensu.LengTeBao));
            if (numCur <= 2)
                btnPrevious.Enabled = false;
            numPrev = numCur - 1;
            if (isCl == 1)//dang chup hinh cho cat lanh
            {
                pre = Left(txtSoTieuBan.Text, 5);
                txtSoTieuBan.Text = pre + numPrev.ToString("0000");
            }
            else// dang chup hinh cho gpb
            {
                pre = Left(txtSoTieuBan.Text, 4);
                txtSoTieuBan.Text = pre + numPrev.ToString("00000");
            }
            btngo_Click(sender, e);
        }

        private void txtSoTieuBan_Validated(object sender, EventArgs e)
        {
            btngo_Click(sender, e);
        }

        private void txtSoTieuBan_Validating(object sender, CancelEventArgs e)
        {
            txtSoTieuBan.Text = txtSoTieuBan.Text.ToUpper();
        }

        private void pic100_Click(object sender, EventArgs e)
        {
            if (btnChupHinh.Enabled == true)
            {
                //p100 = 1;
                btnChupHinh_Click(sender, e);
            }
        }

        private void pic400_Click(object sender, EventArgs e)
        {
            if (btnChupHinhX400.Enabled == true)
            {
                //p400 = 1;
                btnChupHinhX400_Click(sender, e);
            }
        }

        private void frmChupHinh_DS_Activated(object sender, EventArgs e)
        {
         
            /***++++++++++++++++++++++++++++++++++++++++++++++*/
            
            /***++++++++++++++++++++++++++++++++++++++++++++++*/
        }

        private void frmChupHinh_AF_FormClosed(object sender, FormClosedEventArgs e)
        {
            finalFrame.Stop();
        }
    }
}